<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\App;
use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use think\response\Json;
use think\facade\View;
use think\exception\ValidateException;

use app\common\model\CheckList;
use app\common\model\CheckListDetails;
use app\common\model\ProTopic;
use app\common\model\Company;
use app\common\model\District;
use app\common\model\DistrictPro;
use app\common\model\CheckReport;
use app\common\model\User;
use app\common\model\ProPlace;
use app\common\model\Pro as ProModel;

use think\Page;

use app\common\tool\excel\Export;

use app\common\tool\Makezip;

class Pro extends Base
{

    //主键
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Pro';
    protected $ProPlacemodel = '\app\common\model\ProPlace';
    protected $ProNaturemodel = '\app\common\model\ProNature';


    public function index()
    {
        return $this->setTable();
    }

    //自动构建table,按需修改
    public function setTable()
    {
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'field' => '', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80])
            ->addRow(['field' => 'title', 'title' => '项目标题', 'modify' => 'add|edit', 'format' => 'input'])
            ->addRow(['field' => 'num', 'title' => '项目总分数', 'modify' => 'add|edit', 'format' => 'number'])
            ->addRow([
                'field' => 'types',
                'title' => '得分类型',
                'modify' => 'add|edit',
                'templet' => '<span>{{d.types==1?"平均分":"总分"}}</span>',
                'format'    => 'select',
                'value' => [['id' => 1, 'title' => '平均分'], ['id' => 2, 'title' => '总分']]
            ])
            ->addRow(['field' => 'points_ratio', 'title' => '得分比例', 'modify' => 'add|edit', 'format' => 'ratio', 'templet' => '<div>{{(d.points_ratio*100).toFixed(1)}}%</div>'])
            ->addRow([
                'field' => 'sort',
                'title' => '排序',
                'width' => 120,
                'modify' => 'add|edit',
                'format' => 'input',
                // 'templet' => '<div>
                // <input type="text" data-key="sort" data-id="{{d.id}}" data-url="' . url('update') . '" value="{{d.sort}}" class="layui-input x-sort tableInput"/>
                // </div>'
            ])
            ->addRow(['field' => 'create_time', 'title' => '创建时间'])
            ->addRow(['field' => 'update_time', 'title' => '更新时间'])
            ->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 340]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons([
                'edit' => ['width' => 1000, 'height' => 1000],
                'add_proCate' => [
                    'type' => 'edit',
                    'title' => '添加项目分类',
                    'width' => 1400,
                    'height' => 1200,
                    'url' => url('proCate/index', ['name' => request()->controller() . '_' . request()->action()])->build(),
                ],
                // 'add_place' => [
                //     'type' => 'edit',
                //     'title' => '场所性质管理',
                //     'width' => 1400,
                //     'height' => 1200,
                //     'class'  => 'layui-btn layui-btn-sm',
                //     'url' => url('pro/placelist', ['name' => request()->controller() . '_' . request()->action()])->build(),
                // ],

                'delete' => [
                    'type' => 'delete',
                    'title' => '删除',
                    'width' => 1400,
                    'height' => 1200,
                    'class'  => 'layui-btn-danger layui-btn layui-btn-sm right_button',
                    'url' => url('pro/prodel', ['name' => request()->controller() . '_' . request()->action()])->build(),
                ]
            ])

            ->addTopButtons(['add'])
            ->setSearch($this->setSearch())
            ->fetch();
    }
    //自动构建Search，按需修改
    public function setSearch()
    {
        return TableFront::getInstance()
            ->setSearch(['title', '项目标题', 'input', '', '', '', 'like']);
    }

    public function save($param = [], $model = false): Json
    {
        $param = $this->request->post();
        $param['points_ratio'] = round(($param['points_ratio'] / 100), 3);
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }
    /**
     * 隐患统计
     */

    public function statistics()
    {
        $param = $this->request->param();

        $dist = District::where(['is_del' => 0])->order('sort asc')->select();
        if (!$dist->isEmpty()) {
            if (isset($param['district_id'])) {
                $map['district_id'] = $param['district_id'];
            } else {
                $map['district_id'] = $dist[0]['id'];
            }
        } else {
            $map['district_id'] = 0;
        }
        $map['is_del'] = 0;
        $lists = Company::where(['is_del' => 1])->select();
        $list = DistrictPro::where($map)->field('id,district_id,pro_id,basenum')->order('sort asc')->select()->toArray();
        foreach ($list as $k => $v) {
            $count = CheckList::where(array('pro_id' => $v['pro_id'], 'district_id' => $map['district_id'], 'is_del' => 0, 'one_status' => 2))->count();
            $check_list_id = CheckList::where(array('pro_id' => $v['pro_id'], 'district_id' => $map['district_id'], 'is_del' => 0, 'one_status' => 2))->column('id');
            $hgcount = CheckList::where(array('pro_id' => $v['pro_id'], 'district_id' => $map['district_id'], 'is_del' => 0, 'one_status' => 2))->where(['one_score' => 100])->count();

            $pro = $this->model::where(['id' => $v['pro_id'], 'is_del' => 0])->find();
            $v['count'] = $count;
            $v['hgcount'] = $hgcount;
            if ($pro['types'] == 1) {
                $feshu = CheckList::where(['pro_id' => $v['pro_id'], 'is_del' => 0, 'district_id' => $map['district_id'], 'one_status' => 2])->avg('one_score');
            } else {
                $feshu = CheckList::where(['pro_id' => $v['pro_id'], 'is_del' => 0, 'district_id' => $map['district_id'], 'one_status' => 2])->sum('one_score');
            }
            $sum = round(($feshu * $pro['points_ratio']), 1);
            $v['sum'] = $sum;
            $v['title'] = $this->model::where(['id' => $v['pro_id'], 'is_del' => 0])->value('title');
            $v['yhcount'] = CheckListDetails::where(['is_del' => 0])->whereIn('check_list_id', $check_list_id)->count();
            $v['yhhgcount'] = CheckListDetails::where(['is_del' => 0, 'types' => 2])->whereIn('check_list_id', $check_list_id)->count();
            $list[$k] = $v;
        }
        //print('<pre>');print_r($list);die;
        $sort = array_column($list, 'sum');
        array_multisort($sort, SORT_DESC, $list);

        if (isset($param['excelExport'])) {
            $fileName = "检查概况表-" . date('YmdHis') . '.xlsx';
            $headArr = ['场所类别', '检查场所总数', '检查合格场所数', '隐患总数', '整改隐患数', '检查得分'];
            foreach ($list as $k => $v) {
                $data[] = [$v['title'], $v['count'], $v['hgcount'], $v['yhcount'], $v['yhhgcount'], $v['sum']];
            }
            //print('<pre>');print_r($data);die;
            Export::excelExport($headArr, $data, $fileName);
        }
        View::assign('list', $list);
        View::assign('dist', $dist);
        View::assign('district_id', $map['district_id']);
        return View::fetch();
    }
    /** 
     * 隐患统计表
     */

    public function dangerStatistics()
    {

        $param = $this->request->param();
        $list = CheckListDetails::where(['is_del' => 0, 'types' => 1])->field('id,district_id,check_list_id,topic_id')->group('topic_id')->paginate(['list_rows' => 20, 'query' => request()->param()]);
        // print('<pre>');print_r($list->toArray());die;
        /*$lists=Company::where(['is_del'=>1])->select();
         foreach($lists as $kk=>$vv){
            CheckListDetails::where(['company_id'=>$vv['id']])->update(['is_del'=>1]);
            CheckList::where(['company_id'=>$vv['id']])->update(['is_del'=>1]);
         }*/
        foreach ($list as $k => $v) {
            $topic = ProTopic::where(['id' => $v['topic_id'], 'is_del' => 0])->find();
            $count = CheckList::where(['pro_id' => $topic['pro_id'], 'is_del' => 0, 'one_status' => 2])->count();
            $pro = $this->model::where(['id' => $topic['pro_id'], 'is_del' => 0])->find();
            $CheckListDetails = CheckListDetails::where(['topic_id' => $v['topic_id'], 'is_del' => 0, 'types' => 1])->count();
            $v['count'] = $CheckListDetails;
            if ($count != 0) {
                $v['percent'] = round((($CheckListDetails / $count) * 100), 2) . '%';
                $v['percents'] = round((($CheckListDetails / $count) * 100), 2);
            } else {
                $v['percent'] = 0;
                $v['percents'] = 0;
            }

            $v['proname'] = $pro['title'];
            if (!empty($topic)) {
                $v['topictitle'] = limit_text($topic['title'], 60);
            } else {
                $v['topictitle'] = '';
            }
            $list[$k] = $v;
        }


        if (isset($param['excelExport'])) {
            $fileName = "隐患统计表-" . date('YmdHis') . '.xlsx';
            $headArr = ['隐患条款', '所属项目', '隐患比例（隐患条数/已检查场所总数）', '隐患条数'];
            foreach ($list as $k => $v) {
                $data[] = [$v['topictitle'], $v['proname'], $v['percent'], $v['count']];
            }
            Export::excelExport($headArr, $data, $fileName);
        }
        View::assign('list', $list);
        return View::fetch();
    }

    /***
     * 场所隐患清单
     */
    public function placeStatistics()
    {
        $param = $this->request->param();

        $dist = District::where(['is_del' => 0])->order('sort asc')->select();
        if (isset($param['district_id']) && $param['district_id'] != 0) {
            $map[] = ['district_id', '=', $param['district_id']];
            $district_id = $param['district_id'];
        } else {
            $district_id = 0;
        }


        if (isset($param['status']) && $param['status'] != 0) {
            $status = $param['status'];
            $company_id = CheckList::where(['one_status' => $status, 'is_del' => 0])->column('company_id');
            $map[] = ['id', 'in', $company_id];
        } else {
            $status = 0;
        }

        if (isset($param['keyword']) && $param['keyword'] != '' && empty($keyword)) {
            $map[] = ['company_name', 'like', '%' . $param['keyword'] . '%'];
            $keyword = $param['keyword'];
        } else {
            $keyword = '';
        }
        if (isset($param['pro_id']) && $param['pro_id'] != 0) {
            $map[] = ['pro_id', '=', $param['pro_id']];
            //print_r($param);die;
            $pro_id = $param['pro_id'];
        } else {
            $pro_id = 0;
        }
        $map[] = ['is_del', '=', 0];
        $list = Company::where($map)->order('score desc')->paginate(['list_rows' => 10, 'query' => request()->param()]);

        // print_r($list);die;

        foreach ($list as $k => $v) {

            $CheckListDetails = CheckListDetails::where(['company_id' => $v['id'], 'is_del' => 0])->field('id,desc,topic_id,images')->select()->toArray();
            $content = [];
            $contentdesc = [];
            $CheckList = CheckList::where(['company_id' => $v['id'], 'is_del' => 0])->find();
            
            foreach ($CheckListDetails as $kk => $vo) {
                $vo['topicname'] = ProTopic::where(['id' => $vo['topic_id'], 'is_del' => 0])->value('title');

                $vo['imageslist'] = explode(',', $vo['images']);

                $desc = $vo['desc'] != '' ? '不符合描述：' . $vo['desc'] : '';
                $content[] = $vo['topicname'];
                $contentdesc[] =  $desc;

                $CheckListDetails[$kk] = $vo;
            }
            $v['CheckListDetails'] = $CheckListDetails;
            $v['content'] = $content;
            $v['contentdesc'] = $contentdesc;
            $v['yhcount'] = count($CheckListDetails);
            $v['checkname'] =  !empty($CheckList) && $CheckList['one_status'] == 2 ? User::where(['id' => $CheckList['one_uid'], 'is_del' => 0])->value('nickname') : '';
            $v['checktime'] =  !empty($CheckList) && $CheckList['one_status'] == 2 ? $CheckList['one_time'] : '';
            $CheckListfind = CheckList::where(['company_id' => $v['id'], 'is_del' => 0, 'one_status' => 2])->find();
            if (!empty($CheckListfind)) {
                $v['uname'] = User::where(['id' => $CheckListfind['one_uid'], 'is_del' => 0])->value('nickname');
            } else {
                $v['uname'] = '';
            }
            if ($v['status'] == 0) {
                $statusname = '正常';
            } else if ($v['status'] == 1) {
                $statusname = '倒闭';
            } else if ($v['status'] == 2) {
                $statusname = '已搬迁';
            } else if ($v['status'] == 3) {
                $statusname = '责令停工停产';
            } else if ($v['status'] == 4) {
                $statusname = ' 装修中/未营业';
            } else {
                $statusname = '台账重复';
            }

            $CheckList = CheckList::where(['company_id' => $v['id'], 'is_del' => 0, 'one_status' => 2])->value('id');
            $checkReport = CheckReport::where(['check_list_id' => $CheckList])->select();
            if (!empty($checkReport)) {
                foreach ($checkReport as $ks => $vs) {
                    if ($vs['types'] == 4) {
                        $title = '隐患清单';
                    } else if ($vs['types'] == 5) {
                        $title = '隐患复查清单';
                    } else {
                        $title = '检查报告';
                    }
                    $checkReport[$ks]['title'] = $title;
                }
            } else {
                $checkReport = [];
            }
            $v['statusname'] = $statusname;
            $v['checkreport'] = $checkReport;

            $v['proname'] = DistrictPro::where(['id' => $v['place_id'], 'is_del' => 0])->value('title');
            $list[$k] = $v;
        }


        if (isset($param['excelExport'])) {

            Export::exportExcel_1("场所隐患清单-", $list);
        }

        // print('<pre>');print_r($list);die;
        $prolist = $this->model::where(['is_del' => 0])->order('sort asc')->select();

        View::assign('keyword', $keyword);
        View::assign('list', $list);
        View::assign('dist', $dist);
        View::assign('prolist', $prolist);
        View::assign('district_id', $district_id);
        View::assign('pro_id', $pro_id);
        View::assign('status', $status);
        return View::fetch();
    }


    /***
     * 导出场所隐患清单
     */
    public function exportExcelYh()
    {
        $param = $this->request->param();

        $dist = District::where(['is_del' => 0])->order('sort asc')->select();
        if (isset($param['district_id']) && $param['district_id'] != 0) {
            $map[] = ['district_id', '=', $param['district_id']];
            $district_id = $param['district_id'];
        } else {
            $district_id = 0;
        }


        if (isset($param['status']) && $param['status'] != 0) {
            $status = $param['status'];
            $company_id = CheckList::where(['one_status' => $status, 'is_del' => 0])->column('company_id');
            $map[] = ['id', 'in', $company_id];
        } else {
            $status = 0;
        }

        if (isset($param['keyword']) && $param['keyword'] != '' && empty($keyword)) {
            $map[] = ['company_name', 'like', '%' . $param['keyword'] . '%'];
            $keyword = $param['keyword'];
        } else {
            $keyword = '';
        }
        if (isset($param['pro_id']) && $param['pro_id'] != 0) {
            $map[] = ['pro_id', '=', $param['pro_id']];
            //print_r($param);die;
            $pro_id = $param['pro_id'];
        } else {
            $pro_id = 0;
        }
        $map[] = ['is_del', '=', 0];
        $list = Company::where($map)->order('score desc')->select();

        foreach ($list as $k => $v) {
            $v['proname'] = DistrictPro::where(['id' => $v['place_id'], 'is_del' => 0])->value('title');

            $CheckListDetails = CheckListDetails::where(['company_id' => $v['id'], 'is_del' => 0])->field('id,desc,topic_id,images,picture')->select()->toArray();
            $content = [];
            $contentdesc = [];
            $CheckList = CheckList::where(['company_id' => $v['id'], 'is_del' => 0])->find();
            foreach ($CheckListDetails as $kk => $vo) {
                $vo['topicname'] = ProTopic::where(['id' => $vo['topic_id'], 'is_del' => 0])->value('title');
                $vo['imageslist'] = explode(',', $vo['images']);
                $desc = $vo['desc'] != '' ? '不符合描述：' . $vo['desc'] : '';
                $vo['zhenggai'] = !empty($vo['picture']) ? '已整改'  : '未整改';
                $content[] = $vo['topicname'];
                $contentdesc[] =  $desc;
                $CheckListDetails[$kk] = $vo;
            }
            $v['CheckListDetails'] = $CheckListDetails;
            $v['content'] = $content;
            $v['contentdesc'] = $contentdesc;
            $v['yhcount'] = count($CheckListDetails);
            $v['checkname'] =  !empty($CheckList) && $CheckList['one_status'] == 2 ? User::where(['id' => $CheckList['one_uid'], 'is_del' => 0])->value('nickname') : '';
            $v['checktime'] =  !empty($CheckList) && $CheckList['one_status'] == 2 ? $CheckList['one_time'] : '';

            $CheckListfind = CheckList::where(['company_id' => $v['id'], 'is_del' => 0, 'one_status' => 2])->find();
            if (!empty($CheckListfind)) {
                $v['uname'] = User::where(['id' => $CheckListfind['one_uid'], 'is_del' => 0])->value('nickname');
                $v['note_text'] = $CheckListfind['note'];
            } else {
                $v['uname'] = '';
                $v['note_text'] = '';
            }
            if ($v['status'] == 0) {
                $statusname = '正常';
            } else if ($v['status'] == 1) {
                $statusname = '倒闭';
            } else if ($v['status'] == 2) {
                $statusname = '已搬迁';
            } else if ($v['status'] == 3) {
                $statusname = '责令停工停产';
            } else if ($v['status'] == 4) {
                $statusname = ' 装修中/未营业';
            } else {
                $statusname = '台账重复';
            }
            $v['statusname'] = $statusname;
            $list[$k] = $v;
        }

        Export::exportExcel_1("场所隐患清单-", $list);
        return View::fetch();
    }




    //场所性质
    public function placelist($id = '')
    {
        $param = $this->request->param();
        //print($id);die;
        $info = $this->model::where(array('id' => $id))->find();
        if (isset($param['keyword'])) {
            $map['title'] = $param['keyword'];
            $keyword = $param['keyword'];
        } else {
            $keyword = '';
        }
        $map['is_del'] = 0;
        $userlist = $this->ProPlacemodel::where($map)->order('id', 'desc')->paginate(['list_rows' => 20, 'query' => $this->request->param()]);
        foreach ($userlist as $k => $v) {
            $place = $this->ProNaturemodel::where(array('place_id' => $v['id'], 'pro_id' => $id, 'is_del' => 0))->count();
            $v['place'] = $place > 0 ? 1 : 0;
            $userlist[$k] = $v;
        }

        View::assign('info', $info);
        View::assign('keyword', $keyword);
        View::assign('userlist', $userlist);
        return View::fetch();
    }
    //添加场所性质

    public function placeadd(): Json
    {
        $param = $this->request->post();
        try {
            return json($this->ProNaturemodel::placeAdd($param));
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
    }


    //导出为excel文件
    public function exportExcel()
    {
        $param = $this->request->param();
        $fileName = "隐患单位清单-" . date('YmdHis') . '.xlsx';
        $headArr = ['场所/单位名', '所属项目', '场所地址', '消防负责人', '联系电话', '经营面积'];
        $company_id = CheckListDetails::where(['topic_id' => $param['id'], 'is_del' => 0])->column('company_id');
        $list = Company::whereIn('id', $company_id)->select();
        foreach ($list as $k => $v) {
            $pro = $this->model::where(['id' => $v['pro_id']])->value('title');
            $data[] = [$v['company_name'], $pro, $v['address'], $v['fzname'], $v['lxtel'], $v['area']];
        }
        //print('<pre>');print_r($data);die;
        Export::excelExport($headArr, $data, $fileName);
    }

    //打包下载图片
    public function exportImage()
    {
        try {
            $id = $this->request->post('id');
            $company_name = Company::where(['id' => $id, 'is_del' => 0])->value('company_name');
            $company = CheckListDetails::where(['Company_id' => $id, 'is_del' => 0])->column('images');
            $imageslist = explode(',', implode(',', $company));
            $xian = './zip/images/' . $id . '/'; //新文件夹
            foreach ($imageslist as $k => $v) {
                $fidename = explode('/', $v);
                //print_r($fidename);die;
                $yuan = './' . $fidename[1] . '/' . $fidename[2] . '/'; //源文件夹
                dir_copy($yuan, $xian, '.' . $v);
            }
            // print('<pre>');print_r($fidename);die;
            //dir_copy($yuan,$xian,'.'.$v);
            $pdf_url_path = '/zip/zipfile/' . $company_name . '.zip';
            Makezip::zip($xian, '.' . $pdf_url_path);
            return json(['code' => 1, 'msg' => '下载图片成功！', 'url' => $pdf_url_path]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
        //print('<pre>');print_r(dir_copy('./uploads/20230324/','./zip/images/','./uploads/20230324/65067bd07fe790b2467f839876cb2cf5.jpg'));die;
        //return json(['code' => 1, 'msg' => '移动图片成功！', 'url' => $pdf_url_path]);
    }

    /**
     * 原点 2021年7月27日14:46:29 公共删除方法
     */
    public function prodel(): Json
    {
        try {
            $id = $this->request->post('id');

            $model = $this->model::where('id', $id)->find();
            $model->is_del = 1;
            $model->save();
            DistrictPro::where(['pro_id' => $id])->update(['is_del' => 1]);
            return json(['code' => 1, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }
    /**
     * 查看pdf
     */

    public function pdfshowpost(): Json
    {
        $param = $this->request->post();
        try {
            return json(ProModel::pdfShow($param));
        } catch (ValidateException $e) {
            return json(['code' => -1, 'msg' => $e->getError()]);
        }
    }
}
